package com.hndzyu.yd;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.hndzyu.yd.bean.Divide;
import com.hndzyu.yd.bean.LoginResponse;
import com.hndzyu.yd.bean.UserBean;
import com.hndzyu.yd.ui.LoginActivity;
import com.hndzyu.yd.url.Path;
import com.hndzyu.yd.utils.AdPreference;
import com.hndzyu.yd.utils.OkHttpDownloadJsonUtil;
import com.hndzyu.yd.utils.SharedPreferencesUtils;
import com.hndzyu.yd.utils.Util;

import java.io.File;

/**
 * Created by zz9527 on 2018/10/22.
 */
public class SplashActivity extends Activity {


    boolean isRun = true;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mtime--;
            tvdao.setText(mtime + "");
            if (mtime == 0&&isRun) {
                isShareprefence();
                isRun = false;
                finish();
            }
        }
    };


    private ImageView iv_img;
    private int time = 3000;
    private int mtime = 5;
    private TextView tvdao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        iv_img = findViewById(R.id.iv_img);
        View tiaoguo = findViewById(R.id.ll_tiaoguo);
        tvdao = findViewById(R.id.tv_dao);
        imgUrl = AdPreference.getInstance().getStartupAdPage().getRelatedUrl();

        if ("".equals(imgUrl)) {
            tiaoguo.setVisibility(View.GONE);
            mtime=3;
        } else {
            mtime=5;
            tiaoguo.setVisibility(View.VISIBLE);
            tiaoguo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    isShareprefence();
                    isRun = false;
                    finish();

                }
            });
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRun) {
                    try {
                        Thread.sleep(1000);
                        Message message = Message.obtain();
                        message.what = 1;
                        mHandler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
        iv_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!"".equals(imgUrl)) {
                    Uri uri = Uri.parse(imgUrl);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
            }
        });

        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        isFirst();
        if (SharedPreferencesUtils.getDevice(this) == 0) {
            try {
                deviceRegister(Util.androidId(this));
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        getDivide();
    }

    private void isShareprefence(){
        if (SharedPreferencesUtils.getDevice(this) != 0) {
            if ((int) SharedPreferencesUtils.getParam(this, "uid", 0) != 0) {
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
            } else {
                startActivity(new Intent(SplashActivity.this, LoginActivity.class));
            }
        } else {
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
        }
    }
    private void deviceRegister(String device) throws PackageManager.NameNotFoundException {
        Log.i("________channel",Util.getChannel(this));
        OkHttpDownloadJsonUtil.downloadJson(SplashActivity.this, Path.deviceRegister + "?device=" + device+"&channel="+Util.getChannel(this),
                new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        if (!"1".equals(json) && !"2".equals(json)) {
//                            Log.i("_________",json);
                            Gson gson = new Gson();
                            LoginResponse user = gson.fromJson(json, LoginResponse.class);
                            UserBean.uid = user.getData().getUid();
                            UserBean.pid = user.getData().getPid();
                            UserBean.mobile = user.getData().getMobile();
                            UserBean.headimg = user.getData().getAvatar();
                            UserBean.nickname = user.getData().getNickname();
                            UserBean.sex = user.getData().getSex();
                            UserBean.birthday = user.getData().getBirthday();
                            UserBean.job = user.getData().getJob();
                            UserBean.balance = user.getData().getBalance();
                            UserBean.level = user.getData().getLevel();
                            UserBean.gao = user.getData().getGaotype();
                            UserBean.qudao=user.getData().getChannel();
                            SharedPreferencesUtils.setParam(SplashActivity.this, "uid", UserBean.uid);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "mobile", UserBean.mobile);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "headimg", UserBean.headimg);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "nickname", UserBean.nickname);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "sex", UserBean.sex);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "birthday", UserBean.birthday);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "job", UserBean.job);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "balance", UserBean.balance);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "level", UserBean.level);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "gaotype", UserBean.gao);
                            SharedPreferencesUtils.setParam(SplashActivity.this, "qudao", UserBean.qudao);
                            SharedPreferencesUtils.setDevice(SplashActivity.this);
                        } else {
                            Toast.makeText(SplashActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void getDivide() {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.DIVIDE(), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    Gson gson = new Gson();
                    Divide.ParameBean parame = gson.fromJson(json, Divide.class).getParame();
                    UserBean.divide = parame.getTask();
                    UserBean.vipdivide = parame.getViptask();
                    UserBean.carddivide = parame.getCardtask();
                    UserBean.vipcarddivide = parame.getCardviptask();
                    UserBean.ip = parame.getIpconfig();
                    UserBean.subnum=parame.getSubnum();
                    UserBean.subprice=parame.getSubprice();
                    SharedPreferencesUtils.setParam(SplashActivity.this, "divide", UserBean.divide);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "vipdivide", UserBean.vipdivide);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "carddivide", UserBean.carddivide);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "vipcarddivide", UserBean.vipcarddivide);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "ip", UserBean.ip);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "subnum", UserBean.subnum);
                    SharedPreferencesUtils.setParam(SplashActivity.this, "subprice", UserBean.subprice);
                } else {
                    Toast.makeText(SplashActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        });
    }

    String imgUrl = "";

    private void isFirst() {
        String AD_PATH = "";
        AD_PATH = Environment.getExternalStorageDirectory() + "/MFAdYD/" + Util.getImgName(AdPreference.getInstance().getStartupAdPage().getPicUrl());
        File file = new File(AD_PATH);
        Bitmap bm = BitmapFactory.decodeFile(AD_PATH);

        if (file.exists() && bm != null) {
            iv_img.setScaleType(ImageView.ScaleType.FIT_XY);
            iv_img.setImageBitmap(bm);
        } else {
            iv_img.setScaleType(ImageView.ScaleType.FIT_CENTER);
            Util.deleteFile(AD_PATH);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }
}
